<template>
	<view class="use-detail-page">
		<Tips title="小贴士" :des="des" />
		<view class="main">
			<view :ref="listRef" loadmoreoffset="100"  @loadmore="loadmore"  v-if="list.length > 0" class="list-wrap">
			    <view  v-for="(app, i) in list" :key="i" class="list-cell">
					<view class="pointer"><view class="circular"></view></view>
			      <view class="time">
					  <view class="use-date">{{ formatTimeStampToHHMMSS(app.lastStartTime) }} - {{formatTimeStampToHHMMSS(app.lastEndTime)}}</view>
					  <view class="use-time">{{ formatDuration(app.lastStartTime, app.lastEndTime) }}</view>
				  </view>
				  <view class="app-name">
					  <view class="tips">使用了</view>
					  <view class="name">《{{app.appName}}》</view>
				  </view>
				  <view class="app-icon-handler">
					  <view class="app-icon">
						  <image style="width: 36px; height: 36px;" :src="app.appImage" fit="cover"/>
					  </view>
				  </view>
			    </view>
			  </view>
			  <view v-else>
			  	<Empt description="今天暂无使用详情" />
			  </view>
		</view>
		
		<!-- <view class="setup-content" style="display: none;">
			<van-steps v-if="list.length > 0"  :steps="list" :active="list.length" direction="vertical" active-icon="success"
				active-color="#2BC888" inactive-color="#969799" desc-class="custom-desc-class" 	    class="van-steps-component"/>
			<view v-else>
				<Empt description="今天暂无使用详情" />
			</view>
		</view> -->
	</view>
</template>

<script lang="ts" setup>
	import { ref, computed, onMounted } from 'vue'
	import Tips from "@/components/tips/index.vue"
	import Empt from "@/components/Empt/index.vue"
	import { homeServer } from '@/common/index'
	import { useStudentListStore } from "@/stores/useStudentList.js"
	import { imgAddPrefix } from "@/utils/urlHelp"
	import {  mock } from "@/utils/index"
	import { useBound } from "@/hooks/useBound.ts"
	const {tipBoundStudent, studentIsEmpt} = useBound();
		
	const studentStore = useStudentListStore();
	const curStd = computed(() => studentStore.currentStudent);
	const list = ref([]);
	
	const listRef = ref(null)
	const loadmore = () => {
		console.log('加载更多')
	}
	
	function convertMinutesToTimeString(useTime) {  
	    // 检查useTime是否为有效数字  
	    if (typeof useTime !== 'number' || isNaN(useTime) || useTime < 0) {  
	        return '-';  
	    }  
	  
	    // 初始化小时、分钟和秒  
	    let hours = Math.floor(useTime / 60);  
	    let minutes = useTime % 60;  
	    let seconds = 0; // 既然输入是分钟，秒默认是0  
	  
	    // 拼接字符串，根据是否为0决定是否显示小时和分钟  
	    let timeString = '';  
	    if (hours > 0) {  
	        timeString += `${hours}小时`;  
	    }  
	    if (minutes > 0 || (hours === 0 && minutes === 0)) { // 如果小时为0且分钟为0，则不显示；但仅分钟为0且小时不为0时显示  
	        timeString += `${minutes}分`;  
	    }  
	    // 秒始终为0，所以不需要特别处理  
	  
	    // 去除尾随的空格和多余的“分”字  
	    if (timeString.endsWith('分') && timeString.indexOf('小时') === -1) {  
	        timeString = timeString.slice(0, -1);  
	    }  
	  
	    // 如果时间字符串为空（理论上不会发生，除非输入为0分钟且规则不允许显示），则返回"0分"  
	    if (timeString === '') {  
	        timeString = '0分';  
	    }  
	  
	    return timeString;  
	} 
	
	function formatDate(timestamp) {  
	    const date = new Date(timestamp);  
	    const year = date.getFullYear();  
	    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的  
	    const day = String(date.getDate()).padStart(2, '0');  
	    const hours = String(date.getHours()).padStart(2, '0');  
	    const minutes = String(date.getMinutes()).padStart(2, '0');  
	    const seconds = String(date.getSeconds()).padStart(2, '0');  
		    return `${hours}时${minutes}分${seconds}秒`;  
	    // return `${year}年${month}月${day}日${hours}时${minutes}分${seconds}秒`;  
		// return `${year}:${month}:${day}:${hours}:${minutes}:${seconds}`;  
	}  
	  
	function calculateTimeRange(startTime, endTime) {  
	    const start = formatDate(startTime);  
	    const end = formatDate(endTime);  
	    return `${start} - ${end}`;  
	}  
	
	function formatTimeStampToHHMMSS(timeStamp) {  
	    // 创建一个新的Date对象  
	    const date = new Date(timeStamp);  
	  
	    // 提取小时、分钟和秒  
	    const hours = date.getHours().toString().padStart(2, '0'); // 总是两位数  
	    const minutes = date.getMinutes().toString().padStart(2, '0'); // 总是两位数  
	    const seconds = date.getSeconds().toString().padStart(2, '0'); // 总是两位数  
	  
	    // 返回格式化的时间字符串  
	    return `${hours}:${minutes}:${seconds}`;  
	}
	
	
	function formatDuration(startTime, endTime) {  
	    // 计算时间差（毫秒）  
	    const duration = endTime - startTime;  
	  
	    // 初始化小时、分钟、秒  
	    let hours = Math.floor(duration / (1000 * 60 * 60));  
	    let minutes = Math.floor((duration % (1000 * 60 * 60)) / (1000 * 60));  
	    let seconds = Math.floor((duration % (1000 * 60)) / 1000);  
	  
	    // 构造结果字符串  
	    let result = '';  
	    if (hours > 0) {  
	        result += `${hours}小时`;  
	    }  
	    if (minutes > 0 || hours > 0) { // 如果小时大于0，则显示分钟，即使分钟为0  
	        result += `${minutes > 0 ? minutes : ''}${minutes > 0 ? '分' : ''}`;  
	    }  
	    result += `${seconds}秒`;  
	  
	    // 移除末尾不必要的空格（如果有的话）  
	    result = result.replace(/(\d+)([时分秒])$/, '$1$2').trim();  
	  
	    // 如果结果为空（理论上不会发生，但保险起见），返回"0秒"  
	    if (!result) {  
	        return '0秒';  
	    }  
	  
	    return result;  
	}  
	
	
	// 获取使用详情
	const appUseRecordList = async () => {
		const studentId = curStd.value?.id;
		if(!studentId){
			console.log("无法获取学生id")
			return;
		}
		try{
			const {status, data} = await homeServer.appUseRecordList({studentId});
			if(status === '200'){
				list.value = [];
				list.value = data?.map(item => imgAddPrefix(item, 'appImage'));
			}
		}catch(e){
			console.log(e)
			//TODO handle the exception
		}
	}
	// 设置mock数据
	const setMock = () => {
		const data = JSON.parse(JSON.stringify(mock.USE_HISTORY.data));
		list.value = data?.map(item => imgAddPrefix(item, 'appImage'));
	}
	onMounted(() => {
		if(!mock.isLogged()){
			setMock()
		} else {
			appUseRecordList()
		}
	})
	
	
	const des = ref([
		"1.应用统计每15分钟更新一次",
		"2.部分App在后台运行也会算在统计时间内",
		{
			text: '3.使用帮助',
			type: 'usageDetails'
		}

	]);
	const steps = ref([
		{
			text: '2023-07-05 11:17:53',
			desc: '使用了《BOSS直聘》',
		},
		{
			text: '2023-07-05 11:17:53',
			desc: '使用了《百度输入》',
		},
		{
			text: '2023-07-05 11:17:53',
			desc: '使用了《微信》',
		},
		{
			text: '2023-07-05 11:17:53',
			desc: '使用了《QQ》',
		},
	])
</script>

<style lang="scss">
page {
	background-color: #f5f9fa;
}
</style>
<style scoped lang="scss">
	.use-detail-page{
		.setup-content {
			.desc-class {
				font-family: PingFang SC, PingFang SC;
				font-weight: 400;
				font-size: 28px;
				color: #999999;
			}
		}
		
		.main{
			margin-top: 40rpx;
			padding: 40rpx;
			background-color: #fff;
		}
	}
</style>

<style lang="scss">
	.van-steps-component{
		height: 100%;
		padding-bottom: 50upx;
		.van-step{
			padding: 30upx 0;
			.van-step__title{
				line-height: 50upx;
			}
		}
		
	}
	
	
	.list-wrap{
		.list-cell{
			background-color: #fff;
			background-color: #fff;
			padding: 0 50upx 40upx 50upx;
			border-left: 1px dashed #ebebeb;
			width: 90%;
			position: relative;
			&:last-child{
				border: none;
			}
				
			.pointer{
				width:40upx;
				height: 40upx;
				border-radius: 40upx;
				background-color: #d5f4e7;
				display: flex;
				align-items: center;
				justify-content: center;
				position: absolute;
				top: 0;
				left: -11px;
				.circular{
					width:20upx;
					height: 20upx;
					border-radius: 10upx;
					background-color: #2bc888;
				}
			}
				
			.time{
				display: flex;
				justify-content: space-between;
				align-content: center;
				margin-bottom: 10upx;
				.use-date{
					font-size: 28upx;
					font-weight: 400;
					color: #081A2A;
				}
				.use-time{
					font-size: 24upx;
					color: #9999;
					font-weight: 400;
				}
			}
			.app-name{
				display: flex;
				align-items: center;
				justify-content: flex-start;
				font-weight: 400;
				font-size: 28upx;
				color: #999999;
				margin-bottom: 20upx;
				.tips{
					color: #acacac;
				}
				.name{
					color: #0f2130;
					margin-left: 5upx;
				}
			}
			.app-icon-handler{
				.app-icon{
					width: 80upx;
					height: 80upx;
					overflow: hidden;
					border: 10upx;
				}
			}
		}
	}
</style>